"""工具类"""
import functools
from flask import session, current_app, g

from info.models import User


def do_index_class(index):
    """自定义过滤器,过滤点击排序html的class"""
    index_dict = {
        1: "first",
        2: "second",
        3: "third"
    }
    if index in [1, 2, 3]:
        return index_dict[index]
    else:
        return ""


# 以后所有需要判断用户是否登录的借口,直接使用此装饰器函数即可
# 使用装饰器后,视图的函数,会被修改为装饰器的内层函数名, 从而导致重名问题
# 我们希望装饰器装饰的函数,能够保持原始的名字

def user_getter(view_func):
    @functools.wraps(view_func)
    def user_func(*args, **kwargs):
        user_id = session.get("user_id", None)
        user = None
        # 查询用户数据.
        if user_id:
            try:
                user = User.query.get(user_id)
            except Exception as e:
                current_app.logger(e)

        # 将user对象存入g变量中
        g.user = user
        return view_func(*args, **kwargs)

    return user_func
